<template>
	<div class="enhanced-upload">
		<el-upload
			ref="upload"
			action="https://jsonplaceholder.typicode.com/posts/"
			:file-list="internalFileList"
			:list-type="listType"
			:limit="maxCount"
			:accept="accept"
			:headers="uploadHeaders"
			:data="uploadOtherParams"
			:auto-upload="autoUpload"
			:multiple="multiple"
			:drag="drag"
			:on-exceed="handleExceed"
			:before-upload="beforeUpload"
			:on-success="handleSuccess"
			:on-error="handleError"
			:on-remove="handleRemove"
			:before-remove="handleBeforeRemove"
			:on-change="handleChange"
			:on-preview="handlePreview"
			:show-file-list="showFileList"
		>
			<!-- :http-request="handleHttpRequest" -->
			<!-- 默认插槽内容 -->
			<template v-if="drag" class="upload-dragger">
				<i class="el-icon-upload"></i>
				<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
				<div class="el-upload__tip" slot="tip">{{ uploadTip }}</div>
			</template>
			<template v-else>
				<i class="el-icon-plus" v-if="listType == 'picture-card'"></i>
				<el-button size="small" type="primary" v-else>点击上传</el-button>
				<div class="el-upload__tip" slot="tip">{{ uploadTip }}</div>
			</template>
		</el-upload>

		<!-- 错误提示 -->
		<div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>

		<!-- 图片预览对话框 -->
		<el-image-viewer v-if="previewVisible" :urlList="[previewUrl]" :on-close="() => (previewVisible = false)" :zIndex="99999"></el-image-viewer>
	</div>
</template>

<script>
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
// import { getAttachmentListByObjectId, leshanDeleteFile } from "@imms/imms-api";

export default {
	name: "EnhancedUpload",
	components: {
		ElImageViewer,
	},
	props: {
		// 文件列表 - 支持回显的数据格式
		value: {
			type: [Array, String],
		},
		// 列表类型
		listType: {
			type: String,
			default: "picture-card",
			validator: value => ["text", "picture", "picture-card"].includes(value),
		},
		// 最大文件数量
		maxCount: {
			type: Number,
			default: 20,
		},
		// 最大文件大小(MB)
		maxSize: {
			type: Number,
			default: 10,
		},
		// 接受的文件类型
		accept: {
			type: String,
			// default: 'image/*',.
		},
		// 是否自动上传
		autoUpload: {
			type: Boolean,
			default: true,
		},
		// 是否支持多选
		multiple: {
			type: Boolean,
			default: true,
		},
		// 是否启用拖拽
		drag: {
			type: Boolean,
			default: false,
		},
		// 是否显示文件列表
		showFileList: {
			type: Boolean,
			default: true,
		},
	},
	data() {
		return {
			// 内部维护的文件列表
			internalFileList: [],
			errorMessage: "",
			// 图片预览相关
			previewVisible: false,
			previewUrl: "",
			previewTitle: "",
			uploadOtherParams: { objectId: "" }, // 上传文件时携带的参数
		};
	},
	computed: {
		uploadTip() {
			let tip = `只能上传${this.accept}文件`;
			if (this.maxSize) {
				tip += `，且不超过${this.maxSize}MB`;
			}
			if (this.maxCount) {
				tip += `，最多${this.maxCount}个文件`;
			}
			return tip;
		},
		uploadHeaders() {
			return {
				Authorization: "Bearer " + this.$store.getters.token,
			};
		},
	},
	created() {
		this.uploadOtherParams.objectId = this.value;
		// this._getAttachmentListByObjectId();
	},
	methods: {
		// 上传前校验
		beforeUpload(file) {
			this.errorMessage = "";
			// 校验文件类型
			if (this.accept && this.accept !== "*") {
				const acceptTypes = this.accept.split(",").map(type => type.trim());
				const fileExtension = "." + file.name.split(".").pop().toLowerCase();
				const fileType = file.type;

				let isValidType = false;
				for (const type of acceptTypes) {
					if (type.startsWith(".")) {
						// 扩展名匹配
						if (fileExtension === type.toLowerCase()) {
							isValidType = true;
							break;
						}
					} else if (type.endsWith("/*")) {
						// MIME类型前缀匹配
						const mimePrefix = type.split("/*")[0];
						if (fileType.startsWith(mimePrefix)) {
							isValidType = true;
							break;
						}
					} else if (fileType === type) {
						// 完整MIME类型匹配
						isValidType = true;
						break;
					}
				}

				if (!isValidType) {
					this.errorMessage = `文件类型不符合要求，仅支持 ${this.accept} 格式`;
					return false;
				}
			}

			// 校验文件大小
			const isLtMaxSize = file.size / 1024 / 1024 < this.maxSize;
			if (!isLtMaxSize) {
				this.errorMessage = `文件大小不能超过 ${this.maxSize}MB`;
				return false;
			}
			return true;
		},

		// 超出文件数量限制
		handleExceed(files, fileList) {
			this.$message.warning(
				`当前限制选择 ${this.maxCount} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`
			);
		},

		// 文件状态改变 ready-success-error
		handleChange(file, fileList) {},

		// 上传成功
		handleSuccess(response, file, fileList) {
			console.log(response);
			// 后端有判断重复文件。这里需要判断一下，如果重复了,删除掉重复的文件
			// if (response.code == 1 && response.data.length) {
			// 	this.uploadOtherParams.objectId = response.data[0].objectId;
			// 	this.$emit("input", this.uploadOtherParams.objectId);
			// 	// this.$message.success(`${file.name} 上传成功`)
			// } else {
			// 	this.$message.error(`${file.name}` + response.message);
			// 	this.internalFileList = fileList.filter(f => f.uid != file.uid);
			// }
		},

		// 上传失败
		handleError(err, file, fileList) {
			this.$message.error(`${file.name} 上传失败`);
		},

		// 删除文件之前
		handleBeforeRemove(file, fileList) {
			console.log(file, fileList);
			return true;
		},

		// 删除文件
		handleRemove(file, fileList) {
			// 从内部文件列表中移除
			let id = file.id || file.response.data[0].id;
			leshanDeleteFile({ id }).then(res => {
				if (res?.code == 1) {
					if (fileList.length <= 0) {
						this.uploadOtherParams.objectId = "";
						this.$emit("change", "");
					}
				}
			});
		},

		// 文件预览
		handlePreview(file) {
			console.log(file);
			// 图片
			if (this.isImageFile(file)) {
				this.previewImage(file);
				return;
			}
			// 其他文件, pdf 和 txt文件会直接打开页面
			// 为了保存行为一致性，获取文件流直接下载
			fetch(this.createUrl(file))
				.then(res => res.blob())
				.then(blob => {
					const url = URL.createObjectURL(blob);
					console.log(url);
					const link = document.createElement("a");
					link.href = url;
					link.target = "_blank";
					link.download = file.name;
					document.body.appendChild(link);
					link.click();
					document.body.removeChild(link);
				});
		},

		// 预览图片
		previewImage(file) {
			this.previewUrl = this.createUrl(file);
			this.previewTitle = file.name;
			this.previewVisible = true;
		},

		// 根据file文件对象，创建可预览URL
		createUrl(file) {
			if (file.raw) {
				return URL.createObjectURL(file.raw);
			}
			if (file.url) {
				return file.url;
			}
		},

		// 判断是否为图片文件
		isImageFile(file) {
			if (file.raw) {
				return file.raw.type.startsWith("image/");
			}
			if (file.url) {
				const imageExtensions = [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"];
				const extension = file.name.substring(file.name.lastIndexOf(".")).toLowerCase();
				return imageExtensions.includes(extension);
			}
			return false;
		},

		// 提交上传
		submit() {
			this.$refs.upload.submit();
		},

		// 通过附件主id获取附件列表
		_getAttachmentListByObjectId() {
			getAttachmentListByObjectId({ objectId: this.value }).then(res => {
				if (res && res.code == 1 && res.data.length) {
					this.uploadOtherParams.objectId = res.data[0].objectId;
					this.internalFileList = res.data.map(v => {
						return {
							name: v.originalFileName,
							url: `${v.url}?access_token=${this.$store.getters.token}`,
							id: v.id,
							// status: 'uploading',
							// percentage: 70,
						};
					});
				}
			});
		},
	},
};
</script>

<style scoped>
.error-message {
	color: #f56c6c;
	font-size: 12px;
	margin-top: 5px;
}
</style>
